package db

import (
	"example/pkg/message"
	"fmt"
	"github.com/influxdata/influxdb1-client/v2"
	"log"
	"strings"
	"time"
)

type Writer interface {
	Write(wc chan *message.Message)
}

type influxdb struct {
	dns string
}

func (i influxdb) Write(wc chan *message.Message) {
	insli := strings.Split(i.dns,"@")
	fmt.Println(insli)
	c, err := client.NewHTTPClient(client.HTTPConfig{
		Addr: insli[0],
		Username: insli[1],
		Password: insli[2],
	})
	if err != nil {
		log.Fatal(err)
	}
	defer c.Close()

	for v := range wc {
		// Create a new point batch
		bp, _ := client.NewBatchPoints(client.BatchPointsConfig{
			Database:  insli[3],
			//Precision: "infinite",
			Precision: insli[4],
		})
		if err != nil {
			fmt.Println("Error: ", err.Error())
		}
		fmt.Println(wc)
		tags := map[string]string{
			"Path": v.Path,
			"Method": v.Method,
			"Status": v.Status,
			"Scheme": v.Scheme,
			"Brower": v.Browser,
			"Os": v.Os,
		}
		fields := map[string]interface{}{
			"Address": v.Address,
			"Size":   v.Size,
			"LocalTime": v.TimeLocal,
		}
		fmt.Println(tags,fields)
		pt, err := client.NewPoint("nginx_log", tags, fields, time.Now())
		if err != nil {
			fmt.Println("Error: ", err.Error())
		}
		bp.AddPoint(pt)

		err = c.Write(bp)
		if err != nil {
			fmt.Println("Error: ", err.Error())
		}
	}



}
